<?php
/***************************************************************************
 *                              changepass.php
 *                            -------------------
 *                       (APU) Automated Pilot Utility
 *   begin                : Sunday, Dec 5, 2004 - Saturday Nov 25, 2006
 *   copyright            : (C) 2004-2006 SF Games
 *   email                : techsupport@sf-games.com
 *
 *   Expects the following POST variables:
 *
 *            Pilot ID: pilot_id
 *            Password: current_pass
 *        New Password: new_pass1
 *     Verify Password: new_pass2
 ***************************************************************************/

	include_once('common.php');
	include_once('config.php');
	include_once('dbcommon.php');
	include_once('randomQuote.php');

	// Page generation timer start.
	$time = microtime();
	$time = explode(" ", $time);$time = $time[1] + $time[0];$start = $time;

	// Global
	$aErrors = array();

	$db = mysql_connect($dbhost, $dbuname, $dbpass)
		or die("Error: in pirep_submit.php. Could not connect to the SQL server " .mysql_error());
	mysql_select_db($dbname);

	htmlHeader();

	// Gather Form POST variables and validate
	$posted = array("PILOT_ID" => "", "PASSWORD_CURR" => "", "PASSWORD_NEW1" => "", "PASSWORD_NEW2" => "");
	$posted = gatherPost($posted);

	// Validate user id / password combo
	if ( validateUser($posted["PILOT_ID"], $posted["PASSWORD_CURR"]) == false )
		array_push($aErrors, "The Pilot ID and or Password given, is incorrect");

	// Display any errors from the above functions
	if ( count($aErrors) > 0 )
	{
		echo "	<table class=\"table_roster_footer\">\n";
		echo "	<tbody>\n";
		echo "		<tr>\n";
		echo "			<td><span class=\"textred\">\n";
		echo "<div class=\"textdarkCenter\">There are " .count($aErrors) ." submission errors found!<br /><br /></div>\n";

		foreach ($aErrors as $sErr)
			echo $sErr ."<br />\n";

		echo "<div class=\"textdarkCenter\"><br />Press your browsers back button <a href=\"" .$referrer ."\">or here</a> and correct the invalid entries.<br /><br /></div>\n";
		echo "</span></td>\n";
		echo "		</tr>\n";
		echo "	</tbody>\n";
		echo "	<tfoot><tr><td colspan=\"1\"></td></tr></tfoot>\n";
		echo "	</table>\n";
	}
	else
	{
		// Change users password
		if ( changePassword($posted) )
		{
			$query  = 'SELECT PILOT_ID, FIRST_NAME, LAST_NAME, EMAIL FROM ' .$table_prefix .'PILOTS WHERE PILOT_ID = ' .sqlfix($posted["PILOT_ID"]);
			$result = mysql_query($query);
			if ( !$result )
				die("Error: in displayPirep() from pirep_submit.php. Query for Pilot ID in table PILOTS failed. " .mysql_error());
			$pilot = mysql_fetch_array($result, MYSQL_ASSOC);

			// Show success
			displaySuccess($pilot);

			// Send e-mail
			sendPasswordChangedEmail($pilot);
		}
	}

	// Wipe out passwords
	$posted['PASSWORD_CURR'] = "";
	$posted['PASSWORD_NEW1'] = "";
	$posted['PASSWORD_NEW2'] = "";
	if ( isset($_POST['current_pass']) ) unset($_POST['current_pass']);
	if ( isset($_POST['new_pass1']) )    unset($_POST['new_pass1']);
	if ( isset($_POST['new_pass2']) )    unset($_POST['new_pass2']);

	// End page timing
	$time = microtime();$time = explode(" ", $time);$time = $time[1] + $time[0];
	$finish = $time;$totaltime = ($finish - $start);
	$quote = new RandomQuote;
	printf ("This page %s in %f seconds<br/><br/>", $quote->getQuote(), $totaltime);

	htmlFooter();
?>

<?php

			///////////////////////////////////////////
			//                                       //
			//          Support Functions            //
			//                                       //
			///////////////////////////////////////////

//
// Display HTML header
//
function htmlHeader()
{
	echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n";
	echo "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
	echo "<head>\n";
	echo "<title>APU Password Change</title>\n";
	include_once('header.php');

	echo "<style type=\"text/css\" media=\"screen\"> <!-- @import url(apu.css); --> </style>\n";

	echo "</head>\n";
	echo "<body>\n";
	echo "<div align=\"center\">\n";
}

//
// Display HTML footer
//
function htmlFooter()
{
	global $rosterNavigateTo;
	global $rosterNavigateVerbiage;
	global $APU_COPYRIGHT;

	// Display return to another page link/table
	echo "	<table class=\"table_roster_footer\">\n";
	echo "	<tbody>\n";
	echo "		<tr>\n";
	echo "			<td><div align=\"center\"><span class=\"textdark\">Click <a href=\"../" .$rosterNavigateTo ."\">here</a> " .$rosterNavigateVerbiage ."</span></div></td>\n";
	echo "		</tr>\n";
	echo "	</tbody>\n";
	echo "	<tfoot><tr><td colspan=\"1\"></td></tr></tfoot>\n";
	echo "	</table>\n";

	// Display Copyright
	echo "<p>" .$APU_COPYRIGHT ."</p>\n";

	// End HTML
	echo "</div>\n";
	echo "</body>\n";
	echo "</html>\n";
}

//
// Gather POSTed variables from the form submission
//
// Function validates lengths of required variables, strips any HTML and PHP and trims
// the string of leading and trailing white space.
//
// The global $aErrors may contain zero or more errors if any are found.
//
function gatherPost($posted)
{
	include('config.php');
	include('commondefs.php');	// include_once no workie for some dumb reason here. $MAX_ID_LENGTH will not be anything
	global $aErrors;

	// Pilots ID
	if ( isset($_POST['pilot_id']) )
	{
		if ( strlen($_POST['pilot_id']) > 0 && strlen($_POST['pilot_id']) <= $MAX_ID_LENGTH )
		{
			$posted['PILOT_ID'] = strip_tags($_POST['pilot_id']);
			$posted['PILOT_ID'] = trim($posted['PILOT_ID']);

			if ( $bCapitalizedID )
				$posted['PILOT_ID'] = strtoupper($posted['PILOT_ID']);
		}
		else
			array_push($aErrors, "Your Pilot ID is empty or exceeds the allowed length of " .$MAX_ID_LENGTH);
	}

	// Pilots current password
	if ( isset($_POST['current_pass']) )
	{
		if ( strlen($_POST['current_pass']) > 0 && strlen($_POST['current_pass']) <= $MAX_PASSWORD_LENGTH )
		{
			$posted['PASSWORD_CURR'] = strip_tags($_POST['current_pass']);
			$posted['PASSWORD_CURR'] = trim($posted['PASSWORD_CURR']);
		}
		else
			array_push($aErrors, "Your current password is empty or exceeds the allowed length of " .$MAX_PASSWORD_LENGTH);
	}

	// Pilots new password entry #1
	if ( isset($_POST['new_pass1']) )
	{
		if ( strlen($_POST['new_pass1']) > 0 && strlen($_POST['new_pass1']) <= $MAX_PASSWORD_LENGTH )
		{
			$posted['PASSWORD_NEW1'] = strip_tags($_POST['new_pass1']);
			$posted['PASSWORD_NEW1'] = trim($posted['PASSWORD_NEW1']);
		}
		else
			array_push($aErrors, "Your new password, entry #1, is empty or exceeds the allowed length of " .$MAX_PASSWORD_LENGTH);
	}

	// Pilots new password entry #2
	if ( isset($_POST['new_pass2']) )
	{
		if ( strlen($_POST['new_pass2']) > 0 && strlen($_POST['new_pass2']) <= $MAX_PASSWORD_LENGTH )
		{
			$posted['PASSWORD_NEW2'] = strip_tags($_POST['new_pass2']);
			$posted['PASSWORD_NEW2'] = trim($posted['PASSWORD_NEW2']);
		}
		else
			array_push($aErrors, "Your new password, entry #2, is empty or exceeds the allowed length of " .$MAX_PASSWORD_LENGTH);
	}

	//
	// Verify that the changed passwords are the same
	//

	if ( strcmp($posted['PASSWORD_NEW1'], $posted['PASSWORD_NEW2']) != 0 )
		array_push($aErrors, "Your new password, entry #1, does not match your new password entry #2");

	return $posted;
}

//
// Update the pilots record with the new password
//
function changePassword($posted)
{
	include('config.php');

	// Encrypt the new password
	$pencrpyt = md5($posted['PASSWORD_NEW1']);

	$query = "UPDATE " .$table_prefix ."PILOTS SET PASSWORD='$pencrpyt' WHERE PILOT_ID = " .sqlfix($posted['PILOT_ID']);
	$result = mysql_query($query);
	if ( !$result )
		die("Updating of PILOTS record failed.<br/>Click your browsers back button to try again.<br/>If you continue to receive this error, contact the webmaster<br/>Failed with mySQL error: " . mysql_error());

	return true;
}

//
// Success HTML
//
function displaySuccess($pilot)
{
	echo "Thank You " .$pilot['FIRST_NAME'] ." " .$pilot['LAST_NAME'] .", your password has now been changed in the (APU) Automated Pilot Utility.<br/><br/>";
}

//
// Send E-mail
//
function sendPasswordChangedEmail($pilot)
{
	include('config.php');

	$pilotName = $pilot["FIRST_NAME"] ." " .$pilot["LAST_NAME"];

	// Send an E-mail to pilot
	$to = $pilot['EMAIL'];
	$subject   = "Pilot Password Change for " .$pilotName ." - " .$pilot['PILOT_ID'];

	// message
	$message  = "<p class=\"textredBLrg\">" .$vaName ."</p>\n";

	$message .= "<p class=\"textredB\">";
	$message .= $pilotName;
	$message .= " - ";
	$message .= $pilot['PILOT_ID'];
	$message .= "</p>\n";

	$message .= "<hr><br>\n";
	$message .= $pilotName;
	$message .= ", someone, hopefully you, has changed your password in the (APU) Automated Pilot Utility.<br>";
	$message .= "Use your new password, when required, for use in the APU system, such as when submitting PIREP reports.<br><br>";
	$message .= "<hr><br>\n";

	sendEmail("Password Change", $to, $subject, $message);
}

?>
